package com.gandong8.trace.web.core;

import com.gandong8.trace.tool.util.JsonUtil;
import com.gandong8.trace.web.domain.common.Result;
import com.gandong8.trace.web.domain.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public String notFoundHandler( Exception e) {
        //two case /path/hello, /favicon.ico /aa.jpg
        //如果返回Result对象则AbstractMessageConverterMethodProcessor处理器或判断MediaType如果不一致会抛异常
        //org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
        return JsonUtil.toStr(Result.failed(ResultCode.NOT_FOUND));
    }



    /*
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Object notFountHandler(HttpServletRequest request,NoHandlerFoundException e){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/404.html");
        return mv;
    }
     */

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        e.printStackTrace();
        return Result.failed(ResultCode.EXCEPTION);
    }

    @ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
    @ResponseBody
    public Result mediaHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        return Result.failed(ResultCode.EXCEPTION);
    }







}
